package com.muye.dianli.activity;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.entity.mime.content.StringBody;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.Time;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.muye.constant.C;
import com.muye.constant.ConstantPersonalInfo;
import com.muye.constant.U;
import com.muye.dianli.BaseActivity;
import com.muye.dianli.R;
import com.zvezda.algorithm.utils.MD5;
import com.zvezda.http.utils.HttpConst;
import com.zvezda.http.utils.KeyValue;
import com.zvezda.http.utils.RequestHttpListener;
import com.zvezda.http.utils.RequestHttpPostThread;

/**
 * 修改账户页面
 * 
 * @author TangChao
 * 
 */
public class ModifyAccount extends BaseActivity implements OnClickListener, TextWatcher, OnCheckedChangeListener,
		OnKeyListener
{
	/**
	 * 账户
	 */
	private TextView userNameText;
	
	/**
	 * 昵称输入框
	 */
	private EditText inputNickname;
	
	/**
	 * 昵称
	 */
	private String nickname;
	
	/**
	 * 旧密码输入框
	 */
	private EditText inputOldPassword;
	
	/**
	 * 旧密码
	 */
	private String oldPassword;
	
	/**
	 * 新密码输入框
	 */
	private EditText inputNewPassword;
	
	/**
	 * 新密码
	 */
	private String newPassword;
	
	/**
	 * 性别选择框父类
	 */
	private RadioGroup radioGroup;
	
	/**
	 * 男按钮
	 */
	private RadioButton maleBtn;
	
	/**
	 * 女按钮
	 */
	private RadioButton femaleBtn;
	
	/**
	 * 性别
	 */
	private String genderStr;
	
	/**
	 * 生日显示框
	 */
	private TextView birthdayText;
	
	/**
	 * 生日
	 */
	private String birthdayStr;
	
	/**
	 * 地址输入框
	 */
	private EditText inputAddress;
	
	/**
	 * 地址
	 */
	private String address;
	
	/**
	 * 请求数据的线程
	 */
	private RequestHttpPostThread requestHttpPostThread;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getWindow().setFormat(PixelFormat.RGBA_8888);
		setContentView(R.layout.modify_account_layout);
		createTitle();
		initWidget();
		if (ConstantPersonalInfo.sex.equals("1"))
		{
			maleBtn.setChecked(true);
			genderStr = "1";
		}
		else if (ConstantPersonalInfo.sex.equals("2"))
		{
			femaleBtn.setChecked(true);
			genderStr = "2";
		}
	}
	
	@Override
	protected void onDestroy()
	{
		super.onDestroy();
	}
	
	/**
	 * 初始化标题栏
	 */
	private void createTitle()
	{
		TextView titleName = (TextView) findViewById(R.id.title_bar_name_text_view);
		titleName.setText("修改密码");
		titleName.setTextColor(getResources().getColor(R.color.white));
		ImageView leftBtn = (ImageView) findViewById(R.id.title_bar_left_image_view);
		leftBtn.setImageResource(R.drawable.title_back_icon);
		leftBtn.setVisibility(View.VISIBLE);
		leftBtn.setOnClickListener(this);
	}
	
	/**
	 * 初始化控件
	 */
	private void initWidget()
	{
		// 性别选择
		radioGroup = (RadioGroup) findViewById(R.id.modify_account_layout_radio_group);
		radioGroup.setOnCheckedChangeListener(this);
		maleBtn = (RadioButton) findViewById(R.id.modify_account_layout_male_radio_btn);
		femaleBtn = (RadioButton) findViewById(R.id.modify_account_layout_female_radio_btn);
		// 按钮,文本
		userNameText = (TextView) findViewById(R.id.modify_account_layout_user_name);
		userNameText.setText(ConstantPersonalInfo.account);
		birthdayText = (TextView) findViewById(R.id.modify_account_layout_birthday_text);
		birthdayText.setText(ConstantPersonalInfo.birth);
		birthdayStr = ConstantPersonalInfo.birth;
		birthdayText.setOnClickListener(this);
		// 信息输入框
		inputNickname = (EditText) findViewById(R.id.modify_account_layout_nickname_edit);
		inputNickname.setText(ConstantPersonalInfo.name);
		inputNickname.addTextChangedListener(this);
		inputOldPassword = (EditText) findViewById(R.id.modify_account_layout_old_password_edit);
		inputOldPassword.addTextChangedListener(this);
		inputNewPassword = (EditText) findViewById(R.id.modify_account_layout_new_password_edit);
		inputNewPassword.addTextChangedListener(this);
		inputAddress = (EditText) findViewById(R.id.modify_account_layout_address_edit);
		inputAddress.setText(ConstantPersonalInfo.address);
		inputAddress.addTextChangedListener(this);
		// 提交按钮
		TextView submitBtn = (TextView) findViewById(R.id.modify_account_layout_submit);
		submitBtn.setOnClickListener(this);
	}
	
	/**
	 * 请求修改密码
	 */
	private void submitInfo()
	{
		C.openPragressDialog(this, this, R.string.in_request_data);
		ArrayList<KeyValue<String, Object>> paramsList = new ArrayList<KeyValue<String, Object>>();
		String str = address + birthdayStr + nickname + oldPassword + newPassword + genderStr + ConstantPersonalInfo.uid
				+ C.CONSTANT;
		try
		{
			paramsList.add(new KeyValue<String, Object>("address", new StringBody(address, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("birth", new StringBody(birthdayStr, Charset.forName("utf-8"))));
			
			paramsList.add(new KeyValue<String, Object>("name", new StringBody(nickname, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("old", new StringBody(oldPassword, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("pass", new StringBody(newPassword, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("sex", new StringBody(genderStr, Charset.forName("utf-8"))));
			paramsList.add(new KeyValue<String, Object>("uid", new StringBody(ConstantPersonalInfo.uid, Charset
					.forName("utf-8"))));
			paramsList
					.add(new KeyValue<String, Object>("sign", new StringBody(MD5.getMD5_32(str), Charset.forName("utf-8"))));
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		requestHttpPostThread = new RequestHttpPostThread(submitInfoListener, U.SUBMIT_INFO, paramsList);
		requestHttpPostThread.start();
	}
	
	/**
	 * 请求修改密码返回监听
	 */
	private RequestHttpListener submitInfoListener = new RequestHttpListener()
	{
		
		@Override
		public void requestHttp(Message msg)
		{
			Bundle bundle = msg.getData();
			int result = bundle.getInt(HttpConst.ACTION_RESULT, HttpConst.ACTION_FAIL);
			if (result == HttpConst.ACTION_SUCCESS)
			{
				byte[] dataArr = bundle.getByteArray(HttpConst.DATA_ARR);
				try
				{
					String str = new String(dataArr, "utf-8");
				}
				catch (Exception e)
				{
					e.printStackTrace();
				}
				Message message = new Message();
				message.what = 0;
				message.arg1 = result;
				handler.sendMessage(message);
			}
		}
	};
	
	/**
	 * 处理数据
	 */
	private Handler handler = new Handler()
	{
		
		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			C.closePragressDialog();
			switch (msg.what)
			{
				case 0:
					switch (msg.arg1)
					{
						case HttpConst.ACTION_SUCCESS:
							ConstantPersonalInfo.name = inputNickname.getText().toString();
							ConstantPersonalInfo.sex = genderStr;
							ConstantPersonalInfo.birth = birthdayStr;
							ConstantPersonalInfo.address = inputAddress.getText().toString();
							finish();
							break;
						case HttpConst.ACTION_FAIL:
							C.showToast(ModifyAccount.this, "修改失败,请重试");
							break;
						
						default:
							break;
					}
					break;
				
				default:
					break;
			}
		}
		
	};
	
	@Override
	public void onClick(View v)
	{
		switch (v.getId())
		{
			case R.id.title_bar_left_image_view:
				finish();
				break;
			case R.id.modify_account_layout_submit:// 提交按钮
				if (nickname == null || nickname.equals(""))
				{
					C.showToast(this, "昵称不能为空");
					return;
				}
				if (oldPassword == null || oldPassword.equals(""))
				{
					C.showToast(this, "旧密码不能为空");
					return;
				}
				if (birthdayStr == null)
				{
					birthdayStr = "";
				}
				if (address == null)
				{
					address = "";
				}
				submitInfo();
				break;
			case R.id.modify_account_layout_birthday_text:// 生日按钮
				Time time = new Time("GTM-8");
				time.setToNow();
				DatePickerDialog dateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener()
				{
					@Override
					public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
					{
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
						birthdayStr = sdf.format(new Date((year - 1900), monthOfYear, dayOfMonth));
						birthdayText.setText(birthdayStr);
					}
				}, time.year, time.month, time.monthDay);
				dateDialog.show();
				break;
			default:
				break;
		}
	}
	
	@Override
	public void afterTextChanged(Editable s)
	{
		nickname = inputNickname.getText().toString();
		oldPassword = inputOldPassword.getText().toString();
		newPassword = inputNewPassword.getText().toString();
		address = inputAddress.getText().toString();
	}
	
	@Override
	public void beforeTextChanged(CharSequence s, int start, int count, int after)
	{
		
	}
	
	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count)
	{
		
	}
	
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId)
	{
		if (maleBtn.getId() == checkedId)// 男
		{
			genderStr = "1";
		}
		else if (femaleBtn.getId() == checkedId)// 女
		{
			genderStr = "2";
		}
	}
	
	@Override
	public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
	{
		if (requestHttpPostThread != null)
		{
			requestHttpPostThread.interrupt();
			requestHttpPostThread.setRequestHttpListener(null);
		}
		return false;
	}
}
